<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">横向课题上传</span>
        <span style="font-size: 0.8rem; color: #8c8c8c; margin-left: 1vw; line-height: 7vh;">请上传您的横向课题的</span>
        <span style="color: #8c8c8c; line-height: 7vh; font-size: 0.8rem; font-weight: bold;">相关文件：合同书、任务书等。</span>
      </div>

      <pdf-preview
          ref="pdfPreviewRef"
          @update:pdf-path="updatePdfPath"
          @rotations-changed="handleRotationsChanged"
      ></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh;margin-bottom: 3vh">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; display: flex;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">填写信息</span>
          <span style="line-height: 7vh; margin-left: 3vh; color: #CACACA; font-weight: bold">带<span style="color: red;"> * </span>号为必填项</span>
        </div>

        <div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="120px" style="margin-top: 5vh">
            <el-form-item label="课题名称" prop="projectName" required>
              <el-input v-model="ruleForm.projectName" placeholder="请填写课题名称" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="合同来源" prop="contractSource" required>
              <el-input v-model="ruleForm.contractSource" placeholder="如：吉利汽车股份公司" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="合同编号" prop="contractNumber">
              <el-input v-model="ruleForm.contractNumber" placeholder="如：XX" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="到账经费(万)" prop="fundingAmount" required>
              <el-input-number
                  v-model="ruleForm.fundingAmount"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 34vw;"
                  placeholder="如：9.5">
              </el-input-number>
            </el-form-item>

            <el-form-item label="本人排名" prop="rank" required>
              <el-select v-model="ruleForm.rank" placeholder="请选择排名" style="width: 34vw;">
                <el-option
                    v-for="i in 13"
                    :key="i"
                    :label="`第${i}名`"
                    :value="i">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开始时间" prop="startTime" required>
              <el-date-picker
                  v-model="ruleForm.startTime"
                  type="date"
                  placeholder="选择开始日期"
                  style="width: 34vw;"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                  v-model="ruleForm.endTime"
                  type="date"
                  placeholder="选择结束日期"
                  style="width: 34vw;"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="课题状态" prop="projectStatus" >
              <el-select v-model="ruleForm.projectStatus" placeholder="请选择课题状态" style="width: 34vw;">
                <el-option label="在研" value="在研"></el-option>
                <el-option label="结题" value="结题"></el-option>
                <el-option label="终止" value="终止"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="作者信息" prop="authorInfo" required>
              <div style="background-color: #f9f9f9; width: 55vw; height: auto; padding: 10px; border-radius: 4px;">
                <!-- 表头 -->
                <div style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #e8e8e8;">
                  <div style="width: 60px; text-align: center;">排序</div>
                  <div style="width: 100px; margin-left: 10px;">中文名</div>
                  <div style="width: 100px; margin-left: 10px;">作者身份</div>
                  <div style="flex: 1; margin-left: 10px;">单位名称</div>
                  <div style="width: 80px; margin-left: 10px;">操作</div>
                </div>

                <!-- 作者列表 -->
                <div v-for="(author, index) in ruleForm.authorInfo" :key="index" style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0;">
                  <el-select v-model="author.rank" style="width: 60px;">
                    <el-option
                        v-for="item in ruleForm.RankOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <el-input v-model="author.name" style="width: 100px; margin-left: 10px;"></el-input>

                  <el-select v-model="author.identity" style="width: 100px; margin-left: 10px;">
                    <el-option
                        v-for="item in ShipOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <el-select v-model="author.institution" placeholder="单位名称" style="flex: 1; margin-left: 10px;">
                    <el-option label="信息工程学院" value="信息工程学院"></el-option>
                  </el-select>

                  <el-button
                      type="danger"
                      size="small"
                      @click="removeAuthor(index)"
                      style="width: 80px; margin-left: 10px;">
                    删除
                  </el-button>
                </div>

                <el-button @click="addAuthor" style="margin-top: 10px;">添加共同作者</el-button>
              </div>
            </el-form-item>

            <el-form-item label="备注信息" prop="remarks">
              <el-input
                  type="textarea"
                  :rows="4"
                  v-model="ruleForm.remarks"
                  placeholder="请输入备注信息"
                  style="width: 34vw;">
              </el-input>
            </el-form-item>
          </el-form>

          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submit" class="submit-button" :disabled="isSubmitting">
              {{ isSubmitting ? '提交中...' : '提 交' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import PdfPreview from "@/components/PdfPreview.vue"
import { saveHorizontal } from "@/api/Research/Horizontal.js"
import { batchUpdatePdfPages } from "@/api/Manage/File.js";

const router = useRouter()
const ruleFormRef = ref(null)
const pdfPreviewRef = ref(null)
const isSubmitting = ref(false) // 提交状态
const hasRotations = ref(false) // 是否有旋转
const currentRotations = ref([]) // 存储当前的旋转信息

const ShipOptions = [
  { value: '老师', label: '老师' },
  { value: '博士生', label: '博士生' },
  { value: '硕士生', label: '硕士生' },
  { value: '本科生', label: '本科生' },
  { value: '其他', label: '其他' }
]

const ruleForm = reactive({
  projectName: '',
  contractSource: '',
  contractNumber: '',
  fundingAmount: null,
  rank: null,
  startTime: '',
  endTime: '',
  projectStatus: '在研',
  remarks: '',
  pdfPath: '',
  authorInfo: [{
    rank: 1,
    name: '',
    identity: '',
    institution: ''
  }],
  RankOptions: [
    { value: '1', label: '1' },
    { value: '2', label: '2' },
    { value: '3', label: '3' },
    { value: '4', label: '4' },
    { value: '5', label: '5' },
    { value: '6', label: '6' },
    { value: '7', label: '7' },
    { value: '8', label: '8' },
    { value: '9', label: '9' },
    { value: '10', label: '10' },
    { value: '11', label: '11' },
    { value: '12', label: '12' },
    { value: '13', label: '13' }
  ]
})

const identityOptions = [
  { value: '老师', label: '老师' },
  { value: '博士生', label: '博士生' },
  { value: '硕士生', label: '硕士生' },
  { value: '本科生', label: '本科生' },
  { value: '其他', label: '其他' }
]

const rules = reactive({
  projectName: [{ required: true, message: '请输入课题名称', trigger: 'blur' }],
  contractSource: [{ required: true, message: '请输入合同来源', trigger: 'blur' }],
  fundingAmount: [{ required: true, message: '请输入到账经费', trigger: 'blur' }],
  rank: [{ required: true, message: '请选择本人排名', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  authorInfo: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一位作者'))
        } else {
          // 检查每位作者的必填字段
          const hasInvalidAuthor = value.some(author =>
              !author.name || !author.identity || !author.institution || !author.rank
          )
          if (hasInvalidAuthor) {
            callback(new Error('请完善所有作者的信息'))
          } else {
            callback()
          }
        }
      },
      trigger: 'change'
    }
  ]
})

const addAuthor = () => {
  ruleForm.authorInfo.push({
    rank: ruleForm.authorInfo.length + 1,
    name: '',
    identity: '',
    institution: ''
  })
}

const removeAuthor = (index) => {
  ruleForm.authorInfo.splice(index, 1)
}

// 处理旋转状态变化
const handleRotationsChanged = (rotations) => {
  hasRotations.value = rotations.length > 0
  currentRotations.value = rotations
  console.log('旋转状态变化:', rotations)
}

const updatePdfPath = (newPath) => {
  ruleForm.pdfPath = newPath.firstImageUrl
}

const submit = async () => {
  try {
    isSubmitting.value = true
    if (!ruleFormRef.value) return

    await ruleFormRef.value.validate()

    // 如果有旋转，先保存旋转
    if (hasRotations.value && currentRotations.value.length > 0 && ruleForm.pdfPath) {
      try {
        // 组装批量更新请求数据
        const batchData = {
          filePath: ruleForm.pdfPath, // PDF文件路径
          pages: currentRotations.value.map(rotation => ({
            pageNumber: rotation.pageIndex + 1, // 页码从1开始
            rotation: rotation.rotation // 旋转角度
          }))
        }

        console.log('批量更新旋转请求数据:', batchData)

        const rotationResult = await batchUpdatePdfPages(batchData)
        console.log('批量更新旋转结果:', rotationResult)

        if (rotationResult.code !== "0") {
          ElMessage.error('保存旋转失败: ' + (rotationResult.message || '未知错误'))
          return
        }



        // 重置旋转状态
        hasRotations.value = false
        currentRotations.value = []

        // 通知PDF预览组件重新加载
        if (pdfPreviewRef.value && pdfPreviewRef.value.reloadPDF) {
          await pdfPreviewRef.value.reloadPDF(ruleForm.pdfPath)
        }

      } catch (rotationError) {
        console.error('保存旋转失败:', rotationError)
        ElMessage.error('保存旋转失败: ' + (rotationError.message || '网络错误'))
        return
      }
    }

    // 转换日期格式为时间戳
    const formData = {
      ...ruleForm,
      startTime: new Date(ruleForm.startTime).getTime(),
      endTime: new Date(ruleForm.endTime).getTime(),
      authorInfo: JSON.stringify(ruleForm.authorInfo)
    }

    const res = await saveHorizontal(formData)
    if (res.code === 1) {
      ElMessage.success('提交成功')
      router.push("/main/research/Horizontal")
    } else {
      ElMessage.error(res.msg || '提交失败')
    }
  } catch (error) {
    console.error('提交错误:', error)
    if (error.name !== 'ValidationError') {
      ElMessage.error('提交失败，请重试')
    } else {
      ElMessage.error('表单验证失败，请检查必填项')
    }
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.submit-button {
  color: white;
  height: 3.8vh;
  width: 10vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
  border-radius: 4px;
}

.submit-button:hover:not(:disabled) {
  background-color: #009b77;
}

.submit-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-select .el-input__inner) {
  text-align: left;
}
</style>
